<?php

namespace App\Http\Controllers\Service;

use App\Http\Controllers\Service\ServiceController;
use Illuminate\Http\Request;
use App\Http\Components\UserComponent;
use App\Models\UserSettingModel;
use App\Models\ServiceModel;
use App\library\UploadFile;


/**
 * 保存我的服务
 */
class SaveServiceController extends ServiceController{

    public function __construct(){
        parent::__construct();
    }

    /**
     * 版本控制，对应app版本跳转对应接口
     * @param Request $request
     * @author paulLu
     */
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->save_service($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误');
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 保存服务
     */
    public function save_service(Request $request){
        $customAttr = [
            'price' => '每小时价格',
            'advantage' => '一句话描述我的优点',
            'content' => '提供的服务内容',
            'pictures' => '封面图片',
        ];
        $this->validate($request, [
            'price' => 'required|numeric',
            'advantage' => 'required',
            'content' => 'required',
            'pictures' => 'required',
        ],[ ], $customAttr);

        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];

        $price = $request->input('price');
        $advantage = $request->input('advantage');
        $content = $request->input('content');
        $pictures = $request->input('pictures');
        $serviceModel = ServiceModel::where("user_id",$user_id)->first();
        if(!$serviceModel){
            $serviceModel = new ServiceModel();
            $serviceModel->user_id = $user_id;
            $serviceModel->create_time = time();
            $serviceModel->update_time = time();
        }

        $serviceModel->price = $price;
        $serviceModel->advantage = $advantage;
        $serviceModel->content = $content;
        $serviceModel->pictures = $pictures;
        $serviceModel->update_time = time();

        $result = $serviceModel->saveOrFail();


        if($result){
            $UserSettingModel = UserSettingModel::where("user_id",$user_id)->first();
            $UserSettingModel->switch_service=1;
            $UserSettingModel->saveOrFail();
            return $this->json('1','操作成功');
        }else{
            return $this->json('0','操作失败');
        }

    }
}